package com.coocaa.launcher.framework.broadcast;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;

public class HomeKeyReceiver extends BroadcastReceiver {

    private static final String SYSTEM_REASON = "reason";
    private static final String SYSTEM_HOME_KEY = "homekey";
    private static final String SYSTEM_HOME_KEY_LONG = "recentapps";
    private static long lastRevHomeKeyTime = 0L;
    private static List<IHomeKeyBroadcastListener> regList = new ArrayList<IHomeKeyBroadcastListener>();

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        String action = intent.getAction();
        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra(SYSTEM_REASON);
            if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                //表示按了home键,程序到了后台
                callBackToRegister();
            } else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
                //表示长按home键,显示最近使用的程序列表
            }
        }

        if (action.equals("com.android.sky.SendHotKey")) {
            Bundle b = intent.getExtras();
            int keyCode = b.getInt("specialKey");
            if (keyCode == KeyEvent.KEYCODE_HOME) {

                long curremTime = System.currentTimeMillis();

                //测试发现按一次Home会接收到3次广播
                if ((curremTime - lastRevHomeKeyTime) > 100L) {
                    callBackToRegister();
                }

                lastRevHomeKeyTime = curremTime;
            }
        }

    }

    private void callBackToRegister() {
        int i = 0;
        for (i = 0; i < regList.size(); i++) {
            regList.get(i).homeKeyReceiverCallBack();
        }
    }

    public void registerHomeKeyListener(IHomeKeyBroadcastListener i) {
        if (i != null)
            regList.add(i);
    }

    public void unRegisterHomeKeyListener(IHomeKeyBroadcastListener i) {
        if (i != null && regList.contains(i))
            regList.remove(i);
    }

    public interface IHomeKeyBroadcastListener {
        void homeKeyReceiverCallBack();
    }
}
